/**
 * Created by 55456 on 2016/4/11.
 */
var db = require("../models/index");
var Comment = db.models.Comment;
var User = db.models.User;

var addComment = function *(userID,storyID,content){
    try {
        var comment = yield Comment.create({
            content: content,
            UserId: userID,
            StoryId: storyID
        });
        return {status:true,id:comment.id};
    }catch(err){
        console.log(err);
        return {status:false,err:err};
    }
};

var addReply = function *(userID,commentID,content){
    try{
        var comment = yield Comment.findOne({
            where:{
                id:commentID
            }
        });
        if(comment){
            var reply = yield Comment.create({
                content:content,
                UserId:userID,
                StoryId:comment.StoryId
            });
            yield comment.addRevComment(reply);
            return {status:true,id:reply.id};
        }else{
            throw("no such comment,commentID error");
        }
    }catch(err){
        console.log(err);
        return {status:false,err:err};
    }
};

var getAllComment = function *(storyID){
    try{
        var comment = yield Comment.findAll({
            where:{
                StoryId:storyID,
                RevCommentId:{
                    $eq:null
                }
            },
            include:[{
                model:Comment,
                as:"RevComment"
            }]
        });
        return {status:true,comment:comment};
    }catch(err){
        console.log(err);
        return {status:false,err:err};
    }
};

module.exports = {
    addComment,
    addReply,
    getAllComment
};